package com.banksoft.admin.thread;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.AmountType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.dao.AmountLogDao;
import com.banksoft.admin.dao.OrderDao;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.dao.UserMoneyDao;
import com.banksoft.admin.entity.AmountLog;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.entity.UserMoney;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.OrderService;
import com.banksoft.admin.service.UserService;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.util.WeixinUtil;
import com.banksoft.util.DateUtil;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by vanjoger on 2016/9/12.
 */
@Component
public class OrderTask implements InitializingBean {

    @Autowired
    OrderService orderService;
    @Autowired
    BaseService baseService;

    private static boolean isStart = false;
    private static Logger logger = LoggerFactory.getLogger(OrderTask.class);
    private ExecutorService exec = Executors.newCachedThreadPool();

    @Override
    public void afterPropertiesSet() throws Exception {
        if(!isStart){
            logger.info("初始化任务执行....  " + new Date());
           // exec.submit(new OrderCancelTask());
            isStart = true;
        }
    }
    /**
     * 模板消息任务
     */
    class OrderCancelTask implements Runnable{
        @Override
        public void run() {
            while(true){
                logger.info("开始执行定时任务******  " + new Date());
                //取出所有未支付的订单  如果超过24小时未支付  取消
                List<Order> list = orderService.listOrderByStatus(OrderStatus.Create.name());
                if(StringUtil.isNotEmpty(list)) {
                    long now = System.currentTimeMillis();
                    for (Order order : list) {
                        try {
                            long createTime = order.getCreateTime();
                            if ((now - createTime) > 24 * 60 * 60 * 1000) {//超过24小时
                                //如果有未消费的余额  返回
                                if (StringUtil.isNotNull(order.getBonusAmount())) {
                                    String amount = order.getBonusAmount();
                                    if (StringUtil.isNotNull(amount)&&Float.parseFloat(amount) > 0) {
                                        UserMoney money = baseService.findById(UserMoneyDao.class, order.getMemberId());
                                        String beforeBonus = "0";
                                        if (money != null) {
                                            beforeBonus = money.getBonus();
                                            money.setBonus(money.getBonus() + amount);
                                            baseService.update(UserMoneyDao.class, money);
                                        } else {
                                            money = new UserMoney();
                                            money.setId(UUIDFactory.random());
                                            money.setUserId(order.getMemberId());
                                            money.setUserName(order.getUserName());
                                            money.setCash("0");
                                            money.setBonus(amount);
                                            money.setFrozenAmount("0");
                                            money.setTotalAmount(amount);
                                            baseService.insert(UserMoneyDao.class, money);
                                        }

                                        AmountLog log = new AmountLog();
                                        log.setId(UUIDFactory.random());
                                        log.setCreateTime(new Date().getTime());
                                        log.setType(AmountType.TkFee.name());
                                        log.setUserId(order.getMemberId());
                                        log.setBeforeCash(money.getCash());
                                        log.setBeforeBonus(beforeBonus);
                                        log.setBeforeFrozenAmount(money.getFrozenAmount());
                                        log.setCash("0");
                                        log.setBonus(amount );
                                        log.setAfterCash(money.getCash() );
                                        log.setAfterBonus(money.getBonus() );
                                        log.setAfterFrozenAmount(money.getFrozenAmount());
                                        baseService.insert(AmountLogDao.class, log);
                                    }
                                }

                                order.setStatus(OrderStatus.Close.name());
                                baseService.update(OrderDao.class, order);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            continue;
                        }
                    }
                }
                try {
                    Thread.sleep(60 * 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
